﻿package com.agileai.miscdp.hotweb.generator.standard;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Platform;

import com.agileai.miscdp.MiscdpPlugin;
import com.agileai.miscdp.hotweb.domain.ResFileValueProvider;
import com.agileai.miscdp.hotweb.domain.standard.StandardFuncModel;
import com.agileai.miscdp.hotweb.generator.Generator;
import com.agileai.miscdp.util.MiscdpUtil;
import com.agileai.util.StringUtil;

import freemarker.ext.dom.NodeModel;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

/**
 * JSP代码生成器
 */
public class SMJspPagGenerator implements Generator{
	private String listJspFile = null;
	private String detailJspFile = null;
	private File xmlFile = null;
	private String charencoding = "UTF-8";
	private String templateDir = null;
	private StandardFuncModel funcModel = null;
	
	public void generate() {
		String fileName = "template";
		try {
			templateDir = FileLocator.toFileURL(Platform.getBundle(MiscdpPlugin.getPluginId()).getResource(fileName)).getFile().toString();
		} catch (IOException e) {
			MiscdpPlugin.getDefault().logError(e.getLocalizedMessage(), e);
		}
		generateList();
		generateDetail();
		
		if (funcModel.getResFileValueProvider() != null){
			this.generateUploaderPage();
		}
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private void generateList() {
        try {
        	Configuration cfg = new Configuration();
        	cfg.setDirectoryForTemplateLoading(new File(templateDir));
            cfg.setObjectWrapper(new DefaultObjectWrapper());
            cfg.setEncoding(Locale.getDefault(), charencoding);
            String templateFile = "/standard/ListPage.jsp.ftl";
        	Template temp = cfg.getTemplate(templateFile);
        	temp.setEncoding(charencoding);
            Map root = new HashMap();
            NodeModel nodeModel = freemarker.ext.dom.NodeModel.parse(xmlFile);
            root.put("doc",nodeModel);
            File file = new File(listJspFile);
            File parentFile = file.getParentFile();
            if (!parentFile.exists()){
            	parentFile.mkdirs();
            }
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),charencoding));
            temp.process(root, out);
            out.flush();
        } catch (Exception e) {
        	MiscdpPlugin.getDefault().logError(e.getLocalizedMessage(), e);
        }		
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private void generateDetail() {
        try {
        	Configuration cfg = new Configuration();  	
        	cfg.setDirectoryForTemplateLoading(new File(templateDir));
            cfg.setObjectWrapper(new DefaultObjectWrapper());
            cfg.setEncoding(Locale.getDefault(),charencoding);
        	String templateFile = "/standard/DetailPage.jsp.ftl";
        	Template temp = cfg.getTemplate(templateFile);
        	temp.setEncoding(charencoding);
            Map root = new HashMap();
            NodeModel nodeModel = freemarker.ext.dom.NodeModel.parse(xmlFile);
            root.put("doc",nodeModel);
			String uniqueFieldCode = funcModel.retrieveUniqueField(funcModel.getPageFormFields());
			boolean checkUnique = !StringUtil.isNullOrEmpty(uniqueFieldCode);
            root.put("checkUnique", checkUnique);
            
            if (funcModel.getResFileValueProvider() != null){
            	HashMap resFileModel = new HashMap();
            	String primaryKey = funcModel.getPrimaryKey();
            	String tableName = funcModel.getTableName();
            	String handlerId = MiscdpUtil.getValidName(tableName)+"ResouceUploader";
            	resFileModel.put("bizPrimaryKeyField", primaryKey);
            	resFileModel.put("handlerId", handlerId);
            	resFileModel.put("primaryKeyField", funcModel.getResFileValueProvider().getPrimaryKeyField());
            	resFileModel.put("bizIdField", funcModel.getResFileValueProvider().getBizIdField());
            	root.put("resFileModel", resFileModel);
            }else{
            	root.put("resFileModel", "");
            }
            
            File file = new File(this.detailJspFile);
            File parentFile = file.getParentFile();
            if (!parentFile.exists()){
            	parentFile.mkdirs();
            }
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),charencoding));
            temp.process(root, out);
            out.flush();
        } catch (Exception e) {
        	MiscdpPlugin.getDefault().logError(e.getLocalizedMessage(), e);
        }
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	private void generateUploaderPage() {
        try {
        	Configuration cfg = new Configuration();  	
        	cfg.setDirectoryForTemplateLoading(new File(templateDir));
            cfg.setObjectWrapper(new DefaultObjectWrapper());
            cfg.setEncoding(Locale.getDefault(),charencoding);
        	String templateFile = "/fileuploader/UploaderPage.jsp.ftl";
        	Template temp = cfg.getTemplate(templateFile);
        	temp.setEncoding(charencoding);
            Map root = new HashMap();
            HashMap model = new HashMap();
        	String tableName = funcModel.getTableName();
        	String resFileHandlerId = MiscdpUtil.getValidName(tableName)+"ResouceUploader";
        	ResFileValueProvider resFileValueProvider = funcModel.getResFileValueProvider();
        	model.put("handlerId", resFileHandlerId);
        	model.put("bizIdField", resFileValueProvider.getBizIdField());
        	model.put("resIdField", resFileValueProvider.getResIdField());
        	model.put("primaryKeyField", resFileValueProvider.getPrimaryKeyField());
        	root.put("model",model);
        	
        	String uploaderJspFile = MiscdpUtil.parseJspPath(detailJspFile)+"/"+resFileHandlerId+".jsp";;
            File file = new File(uploaderJspFile);
            File parentFile = file.getParentFile();
            if (!parentFile.exists()){
            	parentFile.mkdirs();
            }
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),charencoding));
            temp.process(root, out);
            out.flush();
        } catch (Exception e) {
        	MiscdpPlugin.getDefault().logError(e.getLocalizedMessage(), e);
        }
	}
	
	public String getListJspFile() {
		return listJspFile;
	}
	
	public void setListJspFile(String xmlFile) {
		this.listJspFile = xmlFile;
	}

	public String getDetailJspFile() {
		return detailJspFile;
	}

	public void setDetailJspFile(String detailJspFile) {
		this.detailJspFile = detailJspFile;
	}
	
	public File getXmlFile() {
		return xmlFile;
	}
	
	public void setXmlFile(File xmlFile) {
		this.xmlFile = xmlFile;
	}
	
	public void setFuncModel(StandardFuncModel funcModel) {
		this.funcModel = funcModel;
	}
}